package com.edu.labmanager.controller;


import com.edu.labmanager.common.MyUserDetails;
import com.edu.labmanager.entity.*;
import com.edu.labmanager.service.ILabAdminManagementService;
import com.edu.labmanager.service.ILaboratoryService;
import com.edu.labmanager.service.ISafetyInspectionService;
import com.edu.labmanager.service.ITermService;
import com.edu.labmanager.service.impl.RabbitMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 安全检查登记表，用于记录实验室的安全检查登记信息 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-17
 */
@Controller
@RequestMapping("/safety-inspection")
public class SafetyInspectionController {
    @Autowired
    private ISafetyInspectionService safetyInspectionService;
    @Autowired
    private ILaboratoryService laboratoryService;
    @Autowired
    private ITermService termService;
    @Autowired
    private ILabAdminManagementService iLabAdminManagementService;
    @Autowired
    private RabbitMQProducer rabbitMQProducer;

    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addSafetyInspection(
            @RequestParam Integer laboratoryId,
            @RequestParam Integer termId,
            @RequestParam String inspectionDate,
            @RequestParam String doorWindowCheck,
            @RequestParam String electricalCheck,
            @RequestParam String fireEquipmentCheck,
            @RequestParam String instrumentCheck,
            @RequestParam String itemArrangementCheck,
            @RequestParam String cleanlinessCheck,
            @RequestParam String otherCheck,
            @RequestParam String overallStatus,
            Authentication  authentication) {
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        SafetyInspection safetyInspection = new SafetyInspection();
        safetyInspection.setLaboratoryId(laboratoryId);
        safetyInspection.setTermId(termId);
        safetyInspection.setInspectionDate(LocalDate.parse(inspectionDate));
        safetyInspection.setDoorWindowCheck(doorWindowCheck);
        safetyInspection.setElectricalCheck(electricalCheck);
        safetyInspection.setFireEquipmentCheck(fireEquipmentCheck);
        safetyInspection.setInstrumentCheck(instrumentCheck);
        safetyInspection.setItemArrangementCheck(itemArrangementCheck);
        safetyInspection.setCleanlinessCheck(cleanlinessCheck);
        safetyInspection.setOtherCheck(otherCheck);
        safetyInspection.setOverallStatus(overallStatus);
        safetyInspection.setInspectorId(userDetails.getId());
        if (overallStatus.equals("正常")) {
           safetyInspection.setHandlingTime(LocalDate.now().atStartOfDay());
        } else {
            safetyInspection.setHandlingTime(LocalDate.now().atStartOfDay());

            Laboratory laboratory = laboratoryService.getById(laboratoryId);
            Email email = new Email();
            email.setUserId(1);
            email.setEmail("实验室登记记录"+laboratory.getLaboratoryName()+"的"+otherCheck+"安全检查不通过，请尽快安排人员维修检查");
            //设置当前时间
            email.setCreatedAt(LocalDateTime.now());
            email.setSendperson(userDetails.getUsername());
            email.setLabId(laboratoryId);
            rabbitMQProducer.sendEmail(email);// 或者根据业务设置默认值

        }

        safetyInspectionService.save(safetyInspection);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("redirectUrl", "/safety-inspection/list");
        return ResponseEntity.ok(response);
    }
    @GetMapping("/")
    public String listSafetyInspections1(Model model, Authentication authentication) {
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        //拿到关于当前账户的实验室id
        List<Integer> labIds = iLabAdminManagementService.query().eq("user_id", userDetails.getId()).list()
                .stream().map(LabAdminManagement::getLaboratoryId).collect(Collectors.toList());
        List<Laboratory> laboratories = laboratoryService.listByIds(labIds);
        model.addAttribute("termMap",termService.list().stream().collect(Collectors.toMap(Term::getTermId, Term::getTermName)));
        model.addAttribute("labMap",laboratories.stream().collect(Collectors.toMap(Laboratory::getLaboratoryId, Laboratory::getLaboratoryName)));
        return "safety-add";
    }


    @GetMapping("/list")
    public String listSafetyInspections2(Model model,
                                         @RequestParam(required = false) Integer termId,
                                         @RequestParam(required = false) Integer laboratoryId,
                                         @RequestParam(required = false) String overallStatus,
                                         Authentication  authentication) {
        //拿到关于当前账户的用户id，
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        //模糊查询，只查符合当前用户的安全登记信息
        List<SafetyInspection> inspections = safetyInspectionService.query()
                .eq(termId!=null,"term_id", termId)
                .eq(laboratoryId!=null,"laboratory_id", laboratoryId)
                .eq(overallStatus!=null&& !overallStatus.isEmpty(),"overall_status", overallStatus)
                .eq("inspector_id", userDetails.getId()).list();
        model.addAttribute("inspections", inspections);
        //查询所有学期，用stream流形成 map
        model.addAttribute("termMap",termService.list().stream().collect(Collectors.toMap(Term::getTermId, Term::getTermName)));
        //查询当前用户的实验室，用stream流形成 map
        List<Integer> labids = iLabAdminManagementService.query().eq("user_id", userDetails.getId()).list().stream().map(LabAdminManagement::getLaboratoryId).collect(Collectors.toList());
        if (!labids.isEmpty()) {
            model.addAttribute("labMap", laboratoryService.listByIds(labids).stream().collect(Collectors.toMap(Laboratory::getLaboratoryId, Laboratory::getLaboratoryName)));
        }

        //文章详情页点击返回，通过这里做个判断
        if (hasAuthority(userDetails, "ROLE_admin")) {
            //重定向
            return "redirect:/safety-inspection/admin/list";
        }else{
            return "safety-list";
        }

    }
    public static boolean hasAuthority(UserDetails userDetails, String authority) {
        return userDetails.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals(authority));
    }

    @GetMapping("/admin/list")
    public String listSafetyInspections3(Model model,
                                         @RequestParam(required = false) Integer termId,
                                         @RequestParam(required = false) Integer laboratoryId,
                                         @RequestParam(required = false) String overallStatus
                                         ) {
        List<SafetyInspection> inspections = safetyInspectionService.query()
                .eq(termId!=null,"term_id", termId)
                .eq(laboratoryId!=null,"laboratory_id", laboratoryId)
                .eq(overallStatus!=null&& !overallStatus.isEmpty(),"overall_status", overallStatus).list();
        model.addAttribute("inspections", inspections);
        model.addAttribute("termMap",termService.list().stream().collect(Collectors.toMap(Term::getTermId, Term::getTermName)));
        model.addAttribute("labMap",laboratoryService.list().stream().collect(Collectors.toMap(Laboratory::getLaboratoryId, Laboratory::getLaboratoryName)));
        return "safety-admin-list"; // 对应的 Thymeleaf 页面
    }
    @GetMapping("/detail")
    public String viewSafetyInspectionDetail(@RequestParam Integer id, Model model, Authentication authentication) {
        // 获取安全检查记录
        SafetyInspection inspection = safetyInspectionService.getById(id);

        // 获取实验室和学期名称
        Laboratory lab = laboratoryService.getById(inspection.getLaboratoryId());
        Term term = termService.getById(inspection.getTermId());

        // 添加模型属性
        model.addAttribute("inspection", inspection);
        model.addAttribute("labName", lab != null ? lab.getLaboratoryName() : "未知实验室");
        model.addAttribute("termName", term != null ? term.getTermName() : "未知学期");

        return "safety-detail"; // 返回 Thymeleaf 模板名称
    }

//    @GetMapping("/export")
//    public ResponseEntity<byte[]> exportSafetyInspections(
//            @RequestParam List<Integer> ids,
//            Model model,
//            HttpServletResponse response) throws IOException {
//
//        // 获取要导出的数据
//        List<SafetyInspection> inspections = safetyInspectionService.listByIds(ids);
//
//        // 创建 Excel 工作簿
//        Workbook workbook = new XSSFWorkbook();
//        Sheet sheet = workbook.createSheet("安全检查记录");
//
//        // 设置表头
//        Row headerRow = sheet.createRow(0);
//        String[] headers = {"实验室ID", "学期ID", "检查日期", "整体状态", "处理时间", "检查人ID"};
//        for (int i = 0; i < headers.length; i++) {
//            Cell cell = headerRow.createCell(i);
//            cell.setCellValue(headers[i]);
//            CellStyle style = workbook.createCellStyle();
//            Font font = (Font) workbook.createFont();
//            font.setBold(true);
//            style.setFont(font);
//            cell.setCellStyle(style);
//        }
//
//        // 填充数据
//        int rowNum = 1;
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//        for (SafetyInspection item : inspections) {
//            Row row = sheet.createRow(rowNum++);
//            row.createCell(0).setCellValue(item.getLaboratoryId());
//            row.createCell(1).setCellValue(item.getTermId());
//            row.createCell(2).setCellValue(item.getInspectionDate() != null ? item.getInspectionDate().toString() : "");
//            row.createCell(3).setCellValue(item.getOverallStatus());
//            row.createCell(4).setCellValue(item.getHandlingTime() != null ? item.getHandlingTime().format(formatter) : "");
//            row.createCell(5).setCellValue(item.getInspectorId());
//        }
//
//        // 自动调整列宽
//        for (int i = 0; i < headers.length; i++) {
//            sheet.autoSizeColumn(i);
//        }
//
//        // 输出 Excel 到字节数组
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        workbook.write(outputStream);
//        workbook.close();
//
//        // 构建响应头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        headers.setContentDispositionFormData("attachment", "安全检查记录.xlsx");
//
//        return ResponseEntity.ok()
//                .headers(headers)
//                .body(outputStream.toByteArray());
//    }



}
